//
//  SuperviseCreateTypeVC.swift
//  SBSafetyApp
//
//  Created by Lina on 2023/1/6.
//
// 【首页-检查监督】检查任务-新建

import Foundation
import UIKit

class SuperviseCreateTypeVC: SubLevelViewController {
    let headerV = BSSearchButton(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 60))
    let tableView = UITableView(frame: .zero, style: .plain)
    let submitBtn = UIButton.createPrimaryLarge("下一步，选择网点")

    var rwlxdms: [String] = []
    
    var param: SuperviseParam = SuperviseParam()

    var datas: [SpRwlbModal?]? = []

    var resultV = SpCreateTypeResultView()
    
    var isSearch = false

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        title = "选择任务类型"
        view.backgroundColor = .white
        setupUI()
        
        reloadData()
    }
    
    func reloadData() {
        API.getJcjdRwlb(withParam: SpCommonParam()) { responseModel in
            DispatchQueue.main.async {
                self.datas = responseModel.models
                self.tableView.reloadData()
            }
        }
    }
    
    @objc func confirmTapped() {
        if resultV.rwlxdms.count == 0 && rwlxdms.count == 0  {
            self.view.showToast(witMsg: "请选择任务类型")
        } else {
            if isSearch && resultV.rwlxdms.count > 0 {
                cencelTFTapped()
                param.rwlxdms = resultV.rwlxdms.joined(separator: ",")
            } else {
                param.rwlxdms = rwlxdms.joined(separator: ",")
            }
            branchTapped()
        }
    }
    
    // 选择网点
    func branchTapped() {
        let bSearchVC = BatchBranchSearchVC()
        bSearchVC.didSelectWddmsWith = { (wddms) -> () in
            self.view.showToastActivity()
            self.param.wddms = wddms.joined(separator: ",")
            do {
                let data: Data = try JSONEncoder().encode(self.param)
                let string = String(data: data, encoding: String.Encoding.utf8)
                API.postJcjdCjrw(withParam: CommonJsonParam(jsonStr: string)) { responseModel in
                    DispatchQueue.main.async {
                        self.view.hideToastActivity()
                        if responseModel.errorCode == .Success {
                            Utils.app.window?.showToast(witMsg: "新建成功")
                            NotificationCenter.default.post(name: NotiSupervise, object: nil)
                            let vcs = bSearchVC.navigationController!.viewControllers
                            bSearchVC.navigationController?.popToViewController(vcs[vcs.count - 3], animated: true)
                        } else {
                            self.view.showToast(witMsg: responseModel.errorMessage)
                        }
                    }
                }
            } catch  {
                print("postJcjdCjrw error", error)
            }
        }
        navigationController?.pushViewController(bSearchVC, animated: true)
    }
    
    func setupUI() {
        headerV.titleL.text = "请搜索任务类型"
        headerV.addTarget(self, action: #selector(showSearchTapped), for: .touchUpInside)
        
        submitBtn.addTarget(self, action: #selector(confirmTapped), for: .touchUpInside)
        view.addSubview(submitBtn)
        submitBtn.snp.makeConstraints { make in
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-10)
            make.left.equalTo(view.snp.left).offset(14)
            make.right.equalTo(view.snp.right).offset(-14)
            make.height.equalTo(50)
        }
        
        tableView.dataSource = self
        tableView.delegate = self
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        tableView.backgroundColor = .white
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
            make.bottom.equalTo(submitBtn.snp.top)
        }
        
        tableView.tableHeaderView = headerV
        resultV.headerV.cancelBtn.addTarget(self, action: #selector(cencelTFTapped), for: .touchUpInside)
    }
    
    @objc func showSearchTapped() {
        if resultV.superview == nil {
            isSearch = true
            resultV.datas = datas ?? []
            view.addSubview(resultV)
            resultV.snp.makeConstraints { make in
                make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
                make.left.right.bottom.equalTo(tableView)
            }
            resultV.resetUI()
        }
    }
    
    @objc func cencelTFTapped() {
        if resultV.superview != nil {
            isSearch = false
            resultV.removeFromSuperview()
        }
    }
}

extension SuperviseCreateTypeVC: UITableViewDataSource, UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return datas?.count ?? 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let data = datas?[indexPath.row]
        let ID : String = "SuperviseTypeCell"
            
        var cell = tableView.dequeueReusableCell(withIdentifier: ID)
        if cell == nil {
            cell = SuperviseTypeCell(style: .subtitle, reuseIdentifier: ID)
        }
        
        (cell as? SuperviseTypeCell)?.reload(withSuperviseModal: data!, curs: rwlxdms)
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 50
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let modal = datas?[indexPath.row]
        if (modal?.id != nil && rwlxdms.contains(String(modal!.id!)) == false) {
            rwlxdms.append(String(modal!.id!))
        } else {
            if let index = rwlxdms.firstIndex(of: String(modal!.id!)) {
                rwlxdms.remove(at: index)
            }
        }
        tableView.reloadData()
    }
}

